import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      NProgress.done()
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // 处理用户所拥有的路由权限
        // 明确：个人信息中获取到员工的访问权限的路由信息
        console.log('个人信息', roles.menus)
        console.log('动态路由数组', asyncRoutes)
        // 1.遍历动态路由
        // 2.结合个人信息（数组长度可能是1个，3，5...）一>依次匹配动态路由的名称name
        // 3.一旦匹配成功，添加到路由表中router.addRoutes（[xxx]）
        const filterRoutes = asyncRoutes.filter(item => {
          console.log(item.name)
          return roles.menus.includes(item.name)
        })
        console.log('过滤后的路由', filterRoutes)
        // return router.addRoutes(filterRoutes)
        // 左侧路由菜单
        store.commit('user/setRoutes', filterRoutes)
        // 解决刷新后404页面的bug
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
        next(to.path)// 解决刷新带来的白屏错误 Vue-router3版本已知问题
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})
router.afterEach((to, from) => {
  NProgress.done()
})
